package com.example.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class LockDemo {
    public static void main(String[] args) throws Exception {

        CuratorFramework framework = CuratorFrameworkFactory.builder()
                .connectString("192.168.232.130:2181,192.168.232.130:2182,192.168.232.130:2183")
                .sessionTimeoutMs(5000)// 会话超时时间
                .connectionTimeoutMs(5000)// 连接超时时间
                .namespace("gupao") // 隔离名称
                .retryPolicy(new ExponentialBackoffRetry(1000, 3)) // 重试策略
                .build();

        framework.start();

        InterProcessMutex lock = new InterProcessMutex( framework,"/locks");

        for (int i=0; i<10; i++){
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+" -> 尝试获得锁！");
                try {
                    // 竞争获取锁
                    lock.acquire();
                    System.out.println(Thread.currentThread().getName()+" -> 获得锁！");
                    Thread.sleep(10000);
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    try {
                        // 释放锁
                        lock.release();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        System.in.read();

    }
}
